package com.fsts.client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DecimalFormat;
import java.util.Date;

import javax.swing.JTextArea;

/**
 * 文件接收线程类
 * 
 * 
 * @author
 * @version 1.0
 * @since JDK1.6(建议)
 */
public class ReceiveFile extends Thread {
	JTextArea infoTextArea ;
	public ReceiveFile(JTextArea infoTextArea ) {
		this.infoTextArea = infoTextArea;
	}
	public void run() {
		DataInputStream in = null;
		DataOutputStream out = null;
		FileOutputStream fileOutputStream = null;
		Socket socket = null;
		
		try {
			ServerSocket serverSocket = new ServerSocket(9955);
			while (true) {
				socket = serverSocket.accept();
				in = new DataInputStream(socket.getInputStream());
				out = new DataOutputStream(socket.getOutputStream());
				byte[] b = new byte[1000000];
				// 文件保存路径
				StringBuffer saveFile = new StringBuffer("d:/");
				saveFile.append(in.readUTF());
				File file = new File(saveFile.toString());
				fileOutputStream = new FileOutputStream(file);
				infoTextArea.append("收到文件，正在下载文件>>>>>" + "\n");
				long length = in.readLong();
				DecimalFormat format = new DecimalFormat("###,##0");
				format.setMinimumFractionDigits(2);
				double stat = new Date().getTime();
				while (true) {
					int read = in.read(b);
					if (read == -1) {
						break;
					}
					fileOutputStream.write(b, 0, read);
					infoTextArea.append("已经接收："
									+ format.format(((double) file.length() / length) * 100)
									+ "%\n");
				}
				double end = new Date().getTime();
				infoTextArea.append("消耗时间：" + (end - stat) / 1000 + "\n");
				infoTextArea.append("接受文件完成>>>>\n");
				fileOutputStream.flush();
				out.flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				socket.close();
				fileOutputStream.close();
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
